package net.easyjava.third.db.utils;

import net.easyjava.third.db.annotation.Column;
import net.easyjava.third.db.annotation.ID;
import net.easyjava.third.db.annotation.Table;

import java.lang.reflect.Field;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Created by wxnacy on 16/6/29.
 */
public class DBUtils {
    /**
     * 获取表名
     * @param clazz
     * @return
     */
    public static String getTableName(Class<?> clazz){
        boolean isTable = clazz.isAnnotationPresent(Table.class);
        String name = null;
        if(isTable){
            Table tableTest = clazz.getAnnotation(Table.class);
            name = tableTest.value();
        }else{
            name = clazz.getSimpleName();
        }
        return name;
    }

    /**
     * 获取列名
     * @param field
     * @return
     */
    public static String getColumn(Field field){
        boolean isAnnot = field.isAnnotationPresent(Column.class);
        String column = null;
        if(isAnnot){
            Column col = field.getAnnotation(Column.class);
            column = col.value();
            if("".equalsIgnoreCase(column)){
                column = field.getName();
            }
        }else{
            column = field.getName();
        }
        return column;
    }

    public static String getColumnType(Field field){
        return null;
    }



    /**
     * 判断id是否自增
     * @param clazz
     * @return
     */
    public static boolean idAutoIncrement(Class<?> clazz){
        ID id = clazz.getAnnotation(ID.class);
        if(id == null){
            return false;
        }

        return id.autoIncrement();
    }



    public static void putParmasToPreparedStatement(PreparedStatement ps,Object... params) throws SQLException {
        if(params.length>0){
            for(int i=0;i<params.length;i++){
                Object obj = params[i];
                if(obj instanceof String){
                    ps.setString(i+1,obj.toString());
                }else if(obj instanceof Long){
                    ps.setLong(i+1,Long.valueOf(obj.toString()));
                }else if(obj instanceof Integer){
                    ps.setInt(i+1,Integer.valueOf(obj.toString()));
                }else{
                    ps.setString(i+1,obj.toString());
                }
            }
        }
    }




}
